package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.FirstWarehouse;
import com.ramos.kuaixiao.entity.Product;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StoreNumDB {
    private static String TAG = "StoreNumDB";
    private static String TABLE_NAME = "StoreNum";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
         CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "idx  CHAR(30) PRIMARY KEY  NOT NULL," + "productInfoId" + " CHAR(30) ,"
                + "warehouseId" + " CHAR(30)," + "warehouseName" + " CHAR(30)," + "totalUnitCount" + " INTEGER,"
                + "availableTotalUnitCount" + " INTEGER," + "calcParam" + " INTEGER," + "onSaleCount" + " INTEGER," + "onReturnCount" + " INTEGER," + "total" + " INTEGER," + "modifyTime" + " Long);";


        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllStoreNum(List<FirstWarehouse> customer) {
        //deleteAll();
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM StoreNum");
        String sql = "insert into StoreNum(idx,productInfoId,warehouseId,warehouseName,totalUnitCount,availableTotalUnitCount,calcParam,onSaleCount,onReturnCount,total,modifyTime) values(?,?,?,?,?,?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getIdx() + "");
            stmt.bindString(2, customer.get(i).getProductInfoId() + "");
            stmt.bindString(3, customer.get(i).getWarehouseId() + "");
            stmt.bindString(4, customer.get(i).getWarehouseName() + "");
            stmt.bindString(5, customer.get(i).getTotalUnitCount() + "");
            stmt.bindString(6, customer.get(i).getAvailableTotalUnitCount() + "");
            stmt.bindString(7, customer.get(i).getCalcParam() + "");
            stmt.bindString(8, customer.get(i).getOnSaleCount() + "");
            stmt.bindString(9, customer.get(i).getOnReturnCount() + "");
            stmt.bindString(10, customer.get(i).getTotal() + "");
            stmt.bindString(11, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllStoreNum(List<FirstWarehouse> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllStoreNum:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            FirstWarehouse firstWarehouse = customer.get(i);
            ContentValues cv = new ContentValues();
            cv.put("idx", firstWarehouse.getIdx() + "");
            cv.put("productInfoId", firstWarehouse.getProductInfoId() + "");
            cv.put("warehouseId", firstWarehouse.getWarehouseId() + "");
            cv.put("warehouseName", firstWarehouse.getWarehouseName() + "");
            cv.put("totalUnitCount", firstWarehouse.getTotalUnitCount() + "");
            cv.put("calcParam", firstWarehouse.getCalcParam() + "");
            cv.put("total", firstWarehouse.getTotal() + "");
            cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
            cv.put("availableTotalUnitCount",  (firstWarehouse.getTotalUnitCount() - firstWarehouse.getOnSaleCount()) + "");
            cv.put("onSaleCount", firstWarehouse.getOnSaleCount() + "");
            cv.put("onReturnCount", firstWarehouse.getOnReturnCount() + "");
            Log.i(TAG, "insert:" + firstWarehouse.getAvailableTotalUnitCount() + "");
            db.insertWithOnConflict("StoreNum", null, cv, SQLiteDatabase.CONFLICT_REPLACE); //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }


    public List<FirstWarehouse> findAllStoreNum() {
        List<FirstWarehouse> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        String limit = "1,100";
        String selection = null;
        String[] selectionArgs = null;
        Cursor cursor = db.query("StoreNum", null, selection, selectionArgs, null, null, null, limit);//"5,9",第6行开始,返回9行数据
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            FirstWarehouse orderDetail = new FirstWarehouse();
            orderDetail.setProductInfoId(cursor.getString(1));
            orderDetail.setWarehouseId(cursor.getString(2));
            orderDetail.setWarehouseName(cursor.getString(3));
            orderDetail.setTotalUnitCount(cursor.getInt(4));
            orderDetail.setAvailableTotalUnitCount(cursor.getInt(5));
            orderDetail.setCalcParam(cursor.getInt(6));
            orderDetail.setOnSaleCount(cursor.getInt(7));
            orderDetail.setOnReturnCount(cursor.getInt(8));
            orderDetail.setTotal(cursor.getInt(9));
            orderDetail.setModifyTime(cursor.getLong(10));
            list.add(orderDetail);
        }
        cursor.close();
        //db.close();
        Log.d(TAG, "findAllStoreNum:" + list.size());
        return list;
    }

    public boolean hasStoreNum(String productInfoId, String warehouseId) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from StoreNum where productInfoId =? and warehouseId = ?", new String[]{productInfoId, warehouseId});
        if (cursor.getCount() > 0) {
            cursor.close();
            //Log.d(TAG, "hasStoreNum true");
            return true;
        } else {
            //Log.d(TAG, "hasStoreNum false");
            cursor.close();
            return false;
        }
    }

    public int getStoreNum(String productInfoId, String warehouseId) {
        int num = -1;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from StoreNum where productInfoId =? and warehouseId = ?", new String[]{productInfoId, warehouseId});
        if (cursor.moveToFirst()) {
            num = cursor.getInt(5);
            cursor.close();
            Log.d(TAG, "getStoreNum num" + num);
        } else {
            Log.d(TAG, "getStoreNum false");
            num = 0;
            cursor.close();
        }
        return num;
    }

    public List<Product.WareInfo> getStoreNumList(String productInfoId) {
        List<Product.WareInfo> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from StoreNum where productInfoId=?", new String[]{productInfoId});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            Product.WareInfo customer = new Product.WareInfo();
            customer.setWareHouseId(cursor.getString(2));
            customer.setWareHouseName(cursor.getString(3));
            customer.setCount(cursor.getInt(5));
            list.add(customer);
            Log.d(TAG, "getStoreNumList:" + cursor.getString(3) + " " + cursor.getString(5));
        }

        Set<Product.WareInfo> setData = new HashSet<>();
        setData.addAll(list);
        cursor.close();
        Log.d(TAG, "getStoreNumList:" + list.size());
        return new ArrayList<>(setData);
    }

    public int getParam(String productInfoId) {
        int param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from StoreNum where productInfoId=?", new String[]{productInfoId});
        if (cursor.moveToFirst()) {
            param = cursor.getInt(6);
        }
        cursor.close();
        return param;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from StoreNum ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }


    public int getMaxStoreNum(String productInfoId, String mcustmerId, String custmerName) {
        String custmerId = " ";
        Log.d(TAG, "custmerId:" + mcustmerId + " custmerName: " + custmerName);
        if (mcustmerId.contains("_")) {
            custmerId = mcustmerId.split("_")[1];
        } else {
            custmerId = mcustmerId;
        }
        int num = 0;
        List<Product.WareInfo> list = getStoreNumList(productInfoId);
        if (list.size() == 0) {
            return 0;
        } else {
            String ws = new CustomerWareHouseDB().findCustomer(custmerId + "", custmerName + "");
            List<WareHouse> mWareList = new WareHouseDB().findAllWareHouse(SharedPreference.getPreferString("org"));
            if (mWareList.size() == 0) {
                return 0;
            } else {
                List<WareHouse> tmp;
                if (StringUtil.isEmpty(ws)) {
                    tmp = mWareList;
                } else {
                    tmp = Utils.getList(mWareList, Utils.strToSet(ws));
                }
                Log.d(TAG, "仓库总数:" + list.size());
                for (WareHouse wareHouse : tmp) {
                    //Log.d(TAG, "用户选择的仓库:" + wareHouse.getName());
                }
                List<Product.WareInfo> wareList = Utils.getWare(list, tmp);
                for (Product.WareInfo wareHouse : wareList) {
                    //Log.d(TAG, "有效仓库:" + wareHouse.getWareHouseName());
                }
                Log.d(TAG, "用户选择的仓库:" + tmp.size() + " " + " 本地仓库:" + mWareList.size() + " 有效仓库:" + wareList.size());
                Set<Integer> set = new HashSet<>();
                for (int i = 0; i < wareList.size(); i++) {
                    //Log.d(TAG, "库存数:" + wareList.get(i).getCount());
                    if (wareList.get(i).getCount() > 0) {
                        set.add(wareList.get(i).getCount());
                    }
                }
                if (set.size() > 0) {
                    num = Collections.max(set);
                }
            }
        }
        Log.d(TAG, "getMaxStoreNum:" + num);
        return num;
    }

    public List<Product.WareInfo> getStores(String productInfoId, String mcustmerId, String custmerName) {
        List<Product.WareInfo> mList = new ArrayList<>();
        String custmerId = " ";
        Log.d(TAG, "custmerId:" + mcustmerId + " custmerName: " + custmerName);
        if (mcustmerId.contains("_")) {
            custmerId = mcustmerId.split("_")[1];
        } else {
            custmerId = mcustmerId;
        }
        List<Product.WareInfo> list = getStoreNumList(productInfoId);
        if (list.size() == 0) {
            return mList;
        } else {
            String ws = new CustomerWareHouseDB().findCustomer(custmerId + "", custmerName + "");
            Log.d(TAG, "ws :" + ws);
            List<WareHouse> mWareList = new WareHouseDB().findAllWareHouse(SharedPreference.getPreferString("org"));
            if (mWareList.size() == 0) {
                return mList;
            } else {
                List<WareHouse> tmp;
                if (StringUtil.isEmpty(ws)) {
                    tmp = mWareList;
                } else {
                    tmp = Utils.getList(mWareList, Utils.strToSet(ws));
                }
                //Log.d(TAG, "仓库总数1:" + list.size());
                for (WareHouse wareHouse : tmp) {
                    //Log.d(TAG, "用户选择的仓库1:" + wareHouse.getName());
                }
                if (Utils.getWare(list, tmp).size() > 0) {
                    mList.addAll(Utils.getWare(list, tmp));
                }

                for (Product.WareInfo wareHouse : mList) {
                    //Log.d(TAG, "有效仓库1:" + wareHouse.getWareHouseName());
                }

            }
        }

        return mList;
    }


    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM StoreNum");
        Log.d(TAG, "deleteAllStoreNum ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from StoreNum", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasStoreNum true :" + count);
            return true;
        } else {
            Log.d(TAG, "hasStoreNum false");
            cursor.close();
            return false;
        }
    }

    public void updateNum(String productInfoId, String storeHouseId, String storeHouseName,String calcParam, String largeUnitCount, String smallUnitCount) {
        int num = getStoreNum(productInfoId, storeHouseId) - Integer.valueOf(largeUnitCount) * Integer.valueOf(calcParam) + Integer.valueOf(smallUnitCount);
        if (num > 0) {
            SQLiteDatabase db = DBHelper.open();
            //int newNum = num - (Integer.valueOf(largeUnitCount) * Integer.valueOf(calcParam) + Integer.valueOf(smallUnitCount));
            ContentValues cv = new ContentValues();
            cv.put("availableTotalUnitCount", num + "");
            Log.d(TAG, "updateNum num" + num );
            db.update("StoreNum", cv, "productInfoId=? and warehouseId=? and warehouseName=?", new String[]{productInfoId, storeHouseId, storeHouseName});
        } else {
            SQLiteDatabase db = DBHelper.open();
            ContentValues cv = new ContentValues();
            cv.put("availableTotalUnitCount", "0");
            db.update("StoreNum", cv, "productInfoId=? and warehouseId=? and warehouseName=?", new String[]{productInfoId, storeHouseId, storeHouseName});
        }
    }
}
